import { FC, memo, useEffect, useState } from 'react'
import { LeftConentWrapper } from './style'
import LtSwitch from '@/base-ui/lt-switch'
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { setThemeActions } from '@/store/module/options'
import LtMenu from '@/component/lt-menu'
import { useLocation, useNavigate } from 'react-router-dom'

interface IState {
  children?: React.ReactNode
}

const LeftContent: FC<IState> = memo(() => {
  const disPatch = useAppDispatch()
  const location = useLocation()

  const { theme, asideWidth, menuList, gameList } = useAppSelector(
    (state) => ({
      theme: state.options.theme,
      asideWidth: state.options.asideWidth,
      menuList: state.options.menuList,
      gameList: state.options.gameList
    }),
    shallowEqualApp
  )

  // 计算当前使用的模式文字
  const themeText = () => {
    return theme === 'theme-light' ? '浅色' : '深色'
  }

  // 切换系统主题
  const ltChange = (e: boolean) => {
    if (e) {
      // 设置theme-dark类名
      document.documentElement.setAttribute('class', 'theme-dark')
      localStorage.setItem('theme', 'theme-dark')
    } else {
      document.documentElement.setAttribute('class', 'theme-light')
      localStorage.setItem('theme', 'theme-light')
    }
    disPatch(setThemeActions(e ? 'theme-dark' : 'theme-light'))
  }

  // 计算当前是否展示muen的文字
  const showMenuText = () => {
    return asideWidth === 200 ? true : false
  }

  // 监听路由发生变化
  const [path, setPath] = useState(location.pathname)
  useEffect(() => {
    setPath(location.pathname)
  }, [location])

  const navigatge = useNavigate()
  // 点击菜单触发
  const clickMenu = (data: any) => {
    if (data.img) {
      window.location.href = data.path
    } else {
      navigatge(data.path)
    }
  }

  return (
    <LeftConentWrapper>
      <div className="menu">
        <div className="menu_con">
          <span className="menu_sub">菜单</span>
          {menuList.map((item) => {
            return (
              <LtMenu
                isTitle={showMenuText()}
                key={item.id}
                item={item}
                path={path}
                clickHandle={clickMenu}
              ></LtMenu>
            )
          })}
          <span className="game">游戏</span>
          {gameList.map((item, index) => {
            return (
              <LtMenu
                isTitle={showMenuText()}
                key={index}
                item={item}
                path={path}
                clickHandle={clickMenu}
              ></LtMenu>
            )
          })}
        </div>
      </div>
      <div className="change_theme">
        <LtSwitch ltChange={ltChange} checked={theme === 'theme-dark' ? true : false}></LtSwitch>
        {asideWidth === 200 ? <span className="theme">{themeText()}模式</span> : ''}
      </div>
    </LeftConentWrapper>
  )
})

export default LeftContent
